package com.whiteape.book.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.LinearLayout;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.whiteape.book.R;
import com.whiteape.book.WaApp;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.WebMediaManager;
import com.whiteape.book.model.bo.SearchResultBo;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.MediaChapterBean;
import com.whiteape.book.model.dto.MediaRecordBean;
import com.whiteape.book.model.type.MediaType;
import com.whiteape.book.ui.adapter.ChangeSourceAdapter;
import com.whiteape.book.ui.base.BaseActivity;
import com.whiteape.book.utils.DaoDbHelper;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.widget.RefreshLayout;
import com.whiteape.book.widget.itemdecoration.DividerItemDecoration;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

public class ChangeSourceActivity extends BaseActivity {

    public static final String EXTRA_MEDIA = "extra_media";
    public static final String EXTRA_CHAPTER = "extra_chapter";
    public static final String EXTRA_CHAPTER_LIST = "extra_chapter_list";
    public static final String EXTRA_PAGE = "extra_page";
    public static final String EXTRA_IS_COLLECT = "extra_collect";
    private CollectionMediaBean mCollectionMediaBean;
    private ChangeSourceAdapter mAdapter;
    private List<SearchResultBo> mData;
    private String chapterName;
    private int page;
    private boolean isCollected;
//    private List<MediaChapterBean> inputChapterList;

    @BindView(R.id.rv_content)
    RecyclerView recyclerView;

    @BindView(R.id.refresh_layout)
    RefreshLayout refreshLayout;

    public static void startActivity(Context context, CollectionMediaBean mediaBean,
                                     String chapterName, int page, boolean isCollected) {
        context.startActivity(new Intent(context, ChangeSourceActivity.class)
                .putExtra(EXTRA_MEDIA, mediaBean)
                .putExtra(EXTRA_CHAPTER, chapterName)
                .putExtra(EXTRA_PAGE, page)
                .putExtra(EXTRA_IS_COLLECT, isCollected)
        );
    }

    public static void startActivityForResult(int requestCode, Activity context, CollectionMediaBean mediaBean,
                                     String chapterName, int page, boolean isCollected) {

        context.startActivityForResult(new Intent(context, ChangeSourceActivity.class)
                .putExtra(EXTRA_MEDIA, mediaBean)
                .putExtra(EXTRA_CHAPTER, chapterName)
                .putExtra(EXTRA_PAGE, page)
                .putExtra(EXTRA_IS_COLLECT, isCollected),requestCode
        );
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mCollectionMediaBean = getIntent().getParcelableExtra(EXTRA_MEDIA);
        mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
        chapterName = getIntent().getStringExtra(EXTRA_CHAPTER);
        page = getIntent().getIntExtra(EXTRA_PAGE, 0);
        isCollected = getIntent().getBooleanExtra(EXTRA_IS_COLLECT, false);
//        inputChapterList = (List<MediaChapterBean>)getIntent().getSerializableExtra(EXTRA_CHAPTER_LIST);
        mData = new ArrayList<>();
        mAdapter = new ChangeSourceAdapter(R.layout.item_change_source, mData);
        mAdapter.setCurrentSiteSource(mCollectionMediaBean.getSiteSourceBean());
        mAdapter.setCurrentAuthor(mCollectionMediaBean.getAuthor());

    }

    @Override
    protected void initView() {
        super.initView();
//        getWindow().getDecorView().setBackgroundColor(WaApp.getInstance().getResources().getColor(R.color.statusBarColor));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this));
        recyclerView.setAdapter(mAdapter);

    }

    @Override
    protected int getContentId() {
        return R.layout.activity_change_source;
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("选择网源");
        }
    }

//    private int getMatchedChapterIndex(CollectionMediaBean collectionMediaBean) {
//        try {
//            if (inputChapterList == null || inputChapterList.isEmpty()) {
//                return 0;
//            }
//            String title = inputChapterList.get(chapter).getName().trim();
//            collectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
//            for (int i = 0; i < collectionMediaBean.getMediaChapterList().size(); i ++) {
//                MediaChapterBean chapterBean = collectionMediaBean.getMediaChapterList().get(i);
//                if (chapterBean.getName().trim().equals(title)) {
//                    return i;
//                }
//            }
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return 0;
//
//    }

    @Override
    protected void initEvent() {
        super.initEvent();
        refreshLayout.setOnReloadingListener(this::startLogic);
        mAdapter.setOnItemClickListener(((adapter, view, position) -> {
            //换源了
            CollectionMediaBean collectionMediaBean = new CollectionMediaBean();
            SearchResultBo resultBean = mData.get(position);
            if (resultBean.getSiteSourceBean().getSiteHostUrl().equals(mCollectionMediaBean.getSiteSourceBean().getSiteHostUrl())
            && resultBean.getAuthor().equals(mCollectionMediaBean.getAuthor())) {
                //相同的源
                finish();
                return;
            }
            collectionMediaBean.setMediaType(resultBean.getMediaType());
            collectionMediaBean.setAuthor(resultBean.getAuthor());
            collectionMediaBean.setCoverUrl(resultBean.getCoverUrl());
            collectionMediaBean.setId(resultBean.getDetailUrl());
            collectionMediaBean.setCategory(resultBean.getCategory());
            collectionMediaBean.setDesc(resultBean.getDesc());
            collectionMediaBean.setLastChapter(resultBean.getLastChapter());
            collectionMediaBean.setLastUpdated(resultBean.getLastUpdated());
            collectionMediaBean.setState(resultBean.getState());
            collectionMediaBean.setTitle(resultBean.getTitle());
            collectionMediaBean.setWordCount(resultBean.getWordCount());
            collectionMediaBean.setSiteSourceBean(resultBean.getSiteSourceBean());

            switch (mCollectionMediaBean.getMediaType()) {
                case MediaType.MEDIA_TYPE_NOVEL:
//                    MediaRecordBean newRecord = new MediaRecordBean();
//                    newRecord.setMediaId(collectionMediaBean.getId());
//                    newRecord.setChapter(getMatchedChapterIndex(collectionMediaBean));
//                    newRecord.setPagePos(page);
//                    //TODO
//                    MediaStorageManager.getInstance().saveMediaRecord(newRecord);
                    //先获取详情信息，才能够拿到章节列表的规则
//                    addDisposable(WebMediaManager.getInstance().getMediaInfo(collectionMediaBean)
//                            .compose(RxUtils::toSimpleSingle)
//                            .subscribe(mediaBean -> {
//                                BookReadActivity.startActivity(this, mediaBean, null, false, chapter);
//                            }, Throwable::printStackTrace));
                    setResult(RESULT_OK, new Intent().putExtra("bean", collectionMediaBean));
                    finish();
//                    BookReadActivity.startActivity(this, collectionMediaBean, null, isCollected, -1, chapterName, page);
                    break;
                case MediaType.MEDIA_TYPE_COMIC:
//                    ComicReadActivity.startActivity(this, collectionMediaBean, null, isCollected, null, chapterName, page);
                    setResult(RESULT_OK, new Intent().putExtra("bean", collectionMediaBean));
                    finish();
                    break;

            }
        }));
    }

    @Override
    protected void startLogic() {
        super.startLogic();
        refreshLayout.showLoading();
        Disposable disposable = WebMediaManager.getInstance()
                .getSearchInfoWithMediaType(mCollectionMediaBean.getTitle(), mCollectionMediaBean.getMediaType())
                .compose(RxUtils::toSimpleSingle)
                .subscribe(searchResultBos -> {
                    //展示网源名，小说名，作者名，最新章节
                    List<SearchResultBo> tempList = new ArrayList<>();
                    for (SearchResultBo bo : searchResultBos) {
                        if (bo.getTitle().trim().equals(mCollectionMediaBean.getTitle().trim())) {
                            tempList.add(bo);
                        }
                    }
                    int currentLastOne = mData.size();
                    mData.addAll(tempList);
                    if (mData.size() > 0) {
                        refreshLayout.showFinish();
                    }
                    mAdapter.notifyItemRangeInserted(currentLastOne, tempList.size());

                }, throwable -> refreshLayout.showError());
        addDisposable(disposable);
    }

}
